#pragma once
#include <functional>
#include <iostream>
#include <string.h>
#include <memory>
#include <cstdint>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"
// 错误码
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

static const int gbacklog = 16;
static const int defaultsock = -1;
using func_t = std::function<std::string(const std::string &)>; // 回调函数处理server接收的信息

class tcp_serve;

class thread_data
{
public:
    thread_data(int fd, InetAddr clientaddr, tcp_serve *s)
        : _sockfd(fd), _clientaddr(clientaddr), _self(s)

    {
    }

public:
    InetAddr _clientaddr;
    int _sockfd;
    tcp_serve *_self;
};
class tcp_serve
{
public:
    tcp_serve(uint16_t port, func_t func)
        : _port(port), _func(func), _isruning(false), _listensock(defaultsock)
    {
    }
    void init_serve()
    {
        // 1. 创建流式套接字
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create seccess ,sockfd is : %d\n", _listensock);

        // 2. bind绑定本地协议地址,套接字将用于通信的本地 IP 地址和端口号
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = ::bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success, sockfd is :%d\n", _listensock);
        n = ::listen(_listensock, gbacklog); // 将一个未连接的套接字转换为一个被动套接字，即监听套接字，它可以接受其他套接字的连接请求
        if (n < 0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen success, sockfd is : %d\n", _listensock);
    }
    void service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get new link,info : %s: %d:%d\n", client.Ip(), client.Port(), sockfd);
        std::string clientaddr = "[" + client.Ip() + " : " + std::to_string(client.Port()) + "]#";
        while (true) // 死循环一直接收信息，处理信息，发送信息
        {
            char buffer[1024];
            ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0); // 接收来自套接字sockfd中的信息
            if (n > 0)
            {
                buffer[n] == 0;
                std::cout << clientaddr << buffer << std::endl;

                std::string ret = _func(buffer); // 通过回调函数处理接收的信息

                send(sockfd, ret.c_str(), ret.size(), 0); // 发送处理接受信息的结果给sockfd
            }
            else if (n == 0)
            {
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error \n", clientaddr.c_str());
                break;
            }
        }
        ::close(sockfd);
    }
    static void *handler_sock(void *args)
    {
        std::cout << "2" << std::endl;

        // pthread_detach(pthread_self());
        // thread_data *ptr = static_cast<thread_data *>(args);
        // pthread_detach(pthread_self());
        thread_data *td = static_cast<thread_data *>(args);
        td->_self->service(td->_sockfd, td->_clientaddr);

        delete td;
        return nullptr;
    }
    void loop()
    {
        _isruning = true;
        while (_isruning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensock, (struct sockaddr *)&peer, &len);
            // 用于从监听套接字接受一个连接请求
            // 阻塞等待直到有一个连接请求到达监听套接_listensock
            // 当连接请求到达时，accept会创建一个新的套接字处理这个连接，并返回新套接字的文件描述符。
            // 新套接字用于后续与客户端的通信
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
            pthread_t t;
            std::cout << "1" << std::endl;
            thread_data *td = new thread_data(sockfd, InetAddr(peer), this); // 创建指针td指向thread_data对象
            pthread_create(&t, nullptr, handler_sock, td);                   // 创建一个线程执行handler_sock,并将td'作为参数传递
        }
        _isruning = false;
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isruning;
    func_t _func;
};